package com.web709.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.web709.entity.Activity;
import com.web709.entity.ActivityParticipant;
import com.web709.mapper.ActivityParticipantMapper;
import com.web709.service.ActivityParticipantService;
import com.web709.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ActivityParticipantServiceImpl extends ServiceImpl<ActivityParticipantMapper, ActivityParticipant> implements ActivityParticipantService {
    
    @Autowired
    private ActivityService activityService;
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(Integer id, Integer userId) {
        // 检查是否已参加
        if (hasUserJoined(id, userId)) {
            throw new RuntimeException("您已经参加过该活动");
        }
        
        ActivityParticipant participant = new ActivityParticipant();
        participant.setActivityId(id);
        participant.setUserId(userId);
        participant.setJoinedAt(LocalDateTime.now());
        this.save(participant);
    }

    @Override
    public void removeByActivityId(int activityId) {
        this.remove(new LambdaQueryWrapper<ActivityParticipant>().eq(ActivityParticipant::getActivityId, activityId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveV(Integer id, Integer userId) {
        // 检查是否已参加
        if (hasVolunteerJoined(id, userId)) {
            throw new RuntimeException("您已经参加过该活动");
        }
        
        ActivityParticipant participant = new ActivityParticipant();
        participant.setActivityId(id);
        participant.setVolunteerId(userId);
        participant.setJoinedAt(LocalDateTime.now());
        this.save(participant);
    }


    public boolean hasUserJoined(Integer activityId, Integer userId) {
        LambdaQueryWrapper<ActivityParticipant> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ActivityParticipant::getActivityId, activityId)
               .eq(ActivityParticipant::getUserId, userId);
        return this.count(wrapper) > 0;
    }


    public boolean hasVolunteerJoined(Integer activityId, Integer userId) {
        LambdaQueryWrapper<ActivityParticipant> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ActivityParticipant::getActivityId, activityId)
               .eq(ActivityParticipant::getVolunteerId, userId);
        return this.count(wrapper) > 0;
    }
    
    @Override
    public long countUsersByActivityId(Integer activityId) {
        LambdaQueryWrapper<ActivityParticipant> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ActivityParticipant::getActivityId, activityId)
               .isNotNull(ActivityParticipant::getUserId);
        return this.count(wrapper);
    }

    @Override
    public long countVolunteersByActivityId(Integer activityId) {
        LambdaQueryWrapper<ActivityParticipant> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ActivityParticipant::getActivityId, activityId)
               .isNotNull(ActivityParticipant::getVolunteerId);
        return this.count(wrapper);
    }
    
    @Override
    public List<Map<String, Object>> getParticipationStatistics() {
        // 获取所有活动
        List<Activity> activities = activityService.list();
        
        // 准备结果列表
        List<Map<String, Object>> results = new ArrayList<>();
        
        for (Activity activity : activities) {
            Map<String, Object> stat = new HashMap<>();
            Integer activityId = activity.getId();
            
            // 统计用户和志愿者参与人数
            long userCount = countUsersByActivityId(activityId);
            long volunteerCount = countVolunteersByActivityId(activityId);
            
            // 填充统计数据
            stat.put("activityId", activityId);
            stat.put("activityTitle", activity.getTitle());
            stat.put("userCount", userCount);
            stat.put("volunteerCount", volunteerCount);
            stat.put("totalCount", userCount + volunteerCount);
            
            results.add(stat);
        }
        
        // 按参与总人数降序排序
        results.sort((a, b) -> 
            Long.compare((Long)b.get("totalCount"), (Long)a.get("totalCount")));
        
        return results;
    }
}
